var sys = require("sys"),
    exec = require('child_process').exec,    
    http = require("http"),  
    url = require("url"),  
    querystring =  require("querystring"),
    path = require("path"),  
    fs = require("fs");
    
var crypto = require('crypto');


function render2(response,filename){
    fs.readFile(filename, "binary", function(err, file) {  
        if(err) {  
            response.writeHead(500, {"Content-Type": "text/plain"});  
            response.write(err + "\n");  
            response.end();  
            return;  
        }  

        response.writeHead(200);  
        response.write(file, "binary");  
        response.end();  
    }); 
}

function renderUrlToFile(url, file, width, height, callback) {
  var page = require('webpage').create();
  page.viewportSize = { width: width, height: height };
  page.clipRect = { top: 0, left: 0, width: width, height: height };
  page.settings.userAgent = "PhantomJS/"+phantom_version+" screenshot-webservice/"+version;

  page.open(url, function(status){
    if(status !== "success") {
      console.log("Unable to render '"+url+"' ("+status+")");
      phantom.exit(EXIT_OPEN_FAILED);
    } else {
      page.evaluate(function() {
        document.body.bgColor = 'white';
      });
      page.render(file);
      callback(url, file);
    }
  });
}


function renderUrlToFileWithShell(url,dir,file,callback){
    // 调用shell生成图片
    var cmdstring = "time mkdir -p " + dir +"  && cutycapt --min-width=980 --min-height=1600 --url=" + url + " --out=" + file + " && mogrify " + file +  " -crop 980x2000+0+0 -resize 50%x50% " + file;
    sys.print("exe command: " + cmdstring);
    // executes `pwd`
    var child = exec(cmdstring, function (error, stdout, stderr) {
      sys.print('stdout: ' + stdout);
      sys.print('stderr: ' + stderr);
      if (error !== null) {
         console.log('exec error: ' + error);
      }else{
         callback(url, file);
      }
    });
}

/**
// http://localhost:8080/?target=http://news.17173.com/content/2011-12-25/20111225003713133,1.shtml
function process(request,response){
    
    var params = url.parse(request.url,true).query;
    var destUri = params.target;
    sys.print("fetch the url: " + destUri);
    if(!destUri){
        response.writeHead(500, {"Content-Type": "text/plain"});  
        response.write("the params target is null" + "\n");  
        response.end();  
        return;  
    }

    //var destUri = "http://news.17173.com";
    var md5sum = crypto.createHash('md5');
    var storekey = md5sum.update(destUri).digest("hex") + ".jpg";   
    var filename = path.join(process.cwd(),"images", storekey);  
    sys.puts(filename);
    sys.print("file=" + filename);
    
    path.exists(filename, function(exists) {  
        if(!exists) {  
            renderUrlToFileWithShell(destUri,filename,function(url,file){
                render2(response,file);
                return;
            });

        }else{
            sys.print("file exist:" + filename);
            render2(response,filename);
            sys.print("render end");
            return;
        }         

    });  
    
    sys.print("file end=" + filename);
    
}
**/

  
http.createServer(function(request, response) {  
    //sys.print(querystring.parse(require('url').parse(request.url).query).item);
    //request.addListener('data',function(request,response){
    //    process(request,response);   
    //});
    
    var params = url.parse(request.url,true).query;
    var destUri = params.target;
    sys.print("fetch the url: " + destUri);
    if(!destUri){
        response.writeHead(500, {"Content-Type": "text/plain"});  
        response.write("the params target is null" + "\n");  
        response.end();  
        return;  
    }

    //var destUri = "http://news.17173.com";
    var md5sum = crypto.createHash('md5');
    var storekey = md5sum.update(destUri).digest("hex") + ".jpg";   
    var storedir = path.join(process.cwd(),"images", storekey.substr(0,1));  
    var filename = path.join(storedir, storekey);  
    sys.puts(filename);
    sys.print("file=" + filename);
    
    path.exists(filename, function(exists) {  
        if(!exists) {  
            renderUrlToFileWithShell(destUri,storedir,filename,function(url,file){
                render2(response,file);
                return;
            });

        }else{
            sys.print("file exist:" + filename);
            render2(response,filename);
            sys.print("render end");
            return;
        }         

    });  
    
    sys.print("file end=" + filename);

}).listen(8080);  

  
sys.puts("Server running at http://localhost:8080/");

